import io
import random
import string
from PIL import Image, ImageDraw, ImageFont
import base64

def generate_captcha(text):
    # 创建一个空图像
    width, height = 200, 70
    image = Image.new('RGB', (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(image)

    # 计算合适的字体大小
    font_size = 40  # 初始字体大小
    font = ImageFont.truetype("arial.ttf", font_size)  # 使用系统字体，确保字体文件存在

    # 调整字体大小直到文本占据画布的85%
    while True:
        bbox = draw.textbbox((0, 0), text, font=font)
        text_width = bbox[2] - bbox[0]  # bbox[2]是右下角x坐标，bbox[0]是左上角x坐标
        text_height = bbox[3] - bbox[1]  # bbox[3]是右下角y坐标，bbox[1]是左上角y坐标

        if text_width <= width * 0.85 and text_height <= height * 0.85:
            break
        font_size -= 1
        font = ImageFont.truetype("arial.ttf", font_size)

    # 计算文本位置
    text_x = (width - text_width) // 2
    text_y = (height - text_height) // 2
    draw.text((text_x, text_y), text, fill=(0, 0, 0), font=font)

    # 生成带噪声的图像
    for _ in range(1000):  # 添加1000个噪声点
        x = random.randint(0, width-1)
        y = random.randint(0, height-1)
        draw.point((x, y), fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))

    # 添加条纹、直线和波浪线
    for _ in range(20):  # 添加20条条纹
        start_x = random.randint(0, width)
        start_y = random.randint(0, height)
        end_x = random.randint(0, width)
        end_y = random.randint(0, height)
        draw.line([(start_x, start_y), (end_x, end_y)], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), width=2)

    for _ in range(10):  # 添加10条波浪线
        start_x = random.randint(0, width)
        start_y = random.randint(0, height)
        end_x = random.randint(0, width)
        end_y = random.randint(0, height)
        draw.line([(start_x, start_y), (end_x, end_y)], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), width=2)

    for _ in range(10):  # 添加10条直线
        start_x = random.randint(0, width)
        start_y = random.randint(0, height)
        end_x = random.randint(0, width)
        end_y = random.randint(0, height)
        draw.line([(start_x, start_y), (end_x, end_y)], fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)), width=2)

    # 保存图像到byte流
    buffered = io.BytesIO()
    image.save(buffered, format="PNG")
    img_str = base64.b64encode(buffered.getvalue()).decode()

    return img_str

# 生成一个随机验证码
captcha_text = ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
base64_image = generate_captcha(captcha_text)

# 打印Base64字符串和验证码文本
print("验证码文本:", captcha_text)
print("Base64编码的验证码图像:", base64_image)